package com.marvels.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ThreadContextUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MarvelsLoginInterceptor implements HandlerInterceptor {

	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		MarvelsLogUtil.getInstance().info("MarvelsLoginInterceptor.preHandle request url===>"+request.getRequestURI());
		String token = request.getHeader("l-token");
		ThreadContextUtil.set("l-token", token);
		String loginUUid = request.getHeader("l-loginUUid");
		ThreadContextUtil.set("l-loginUUid", loginUUid);
		if(!CacheUtils.isLogin()){
			response.setContentType(MarvelsConstant.CONTENT_TYPE_JSON);
			MarvelsResultDTO result = MarvelsResultDTO.getResult(MarvelsErrorCode.USER_NOT_LOGGED.getValue(), MarvelsErrorCode.USER_NOT_LOGGED.getDesc(), null);
			CacheUtils.delCacheUser();
			ThreadContextUtil.removeAll();
			response.getWriter().print(JSONObject.toJSONString(result));
			return false;
		}
		// 刷新登陆时效
		CacheUtils.refreshLoginTime(token);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		ThreadContextUtil.removeAll();
	}
	
}
